import Stomp from "stompjs";

export default {
  newInstance(v) {
    return this.instance = {
      subList:{},
      msgEvtPrefix:"ws-subscribe-msg-",
      getConnected(url, connectConfig) {
        this.config = connectConfig || {
          "login": "epWeb",
          "passcode": "159753EpWeb",
          "host": "epWeb",
          "heart-beat": "0,0"
        };
        let wsProtocol = window.location.protocol === "https:" ? "wss" : "ws";
        // this.client = Stomp.client(url || window.location.protocol+"//huancehuanbao.com/wss");
        this.client = Stomp.client(url || "ws://47.108.57.101:15674/ws");
        this.client.__proto__.debug=()=>{};
        return this;
      },
      connect(successCb, failCb) {
        this.client.connect(this.config, successCb || this.onConnected, failCb || this.onFailed);
        return this;
      },
      onConnected(frame) {
        v.$ge.$emit("ws-connect-success", frame);
        return this;
      },
      subscribe(exchange, rk, onMsg) {
        let self=this.isOk();
        v.$ge.$on("ws-connect-success",()=>{
          this.client.subscribe("/exchange/"+exchange+"/"+rk, onMsg || function (frame) {
            v.$ge.$emit(self.msgEvtPrefix+rk, frame.body);
          });
          if(self.subList[exchange]){
            self.subList[exchange].push(rk);
            self.isOk(null,1)
            return;
          }
          self.subList[exchange]=[rk];
          self.isOk(null,1)
        });
        return this;
      },
      isOk(cb,ok){
        if(!cb){
          this.status=ok;
          return this;
        }
        let self=this,ck=setInterval(()=>{
          if(self.status){
            try{
              cb(self.subList);
            }catch (e){
              console.error(e);
            }
            clearInterval(ck);
          }
        },100)
        return this;
      },
      onFailed(frame) {
        v.$ge.$emit("ws-connect-fail", frame);
        return this;
      }
    }
  }
}
